package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {

    /**
     * 处理数据库唯一操作
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R SQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e){
        log.debug("唯一异常");
        //Duplicate entry
        if (e.getMessage().contains("Duplicate entry")){
            String errorMessage = e.getMessage().split(" ")[2].replace("'", "");
            return R.error(errorMessage + " 存在");
        }
        return R.error("系统繁忙，请稍后再试");
    }

    /**
     * 处理删除菜品分类时，因为包含其他内容不能删除的异常
     * @param e
     * @return
     */
    @ExceptionHandler(IncludeOtherException.class)
    public R IncludeOtherException(IncludeOtherException e){
        String errorMessage = e.getMessage();
        return R.error(errorMessage);
    }
}
